﻿using PrjAssessModels.BaseModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PrjAssess.Models
{
    public class ParameterHelper
    {
        public string PrjId { get; set; }
        public List<ParaItem> ParaItems { get; set; }
        public bool IsCustom { get; set; }
        public ParameterHelper(string pId = "default")
        {
            this.PrjId = pId;
            ParaItems = new List<ParaItem>();
            using(var db = new PrjAssessDb())
            {
                var list = db.ParaItems.Where(p => p.PrjId == pId);
                if (list.Count() > 0)
                {
                    this.ParaItems = list.ToList();
                    this.IsCustom = true;
                }
                else
                {
                    this.ParaItems = db.ParaItems.Where(p => p.PrjId == "default").ToList();
                    this.IsCustom = false;
                }
            }
        }

        public bool Update(ParaItem[] items)
        {

            using (var db = new PrjAssessDb())
            {
                if (this.IsCustom == true)
                {
                    var list = db.ParaItems.Where(p => p.PrjId == this.PrjId);
                    foreach (var item in list)
                    {
                        db.ParaItems.Remove(item);
                    }
                }
                foreach (var item in items)
                {
                    item.PrjId = this.PrjId;
                    db.ParaItems.Add(item);
                }
                db.SaveChanges();
                return true;
            }
       
        }
        public double this[string key,string group]
        {
            get
            {
                var items = this.ParaItems.Where(p => p.GroupName == group);
                var item = items.SingleOrDefault(p => p.Content == key);
                return item == null ? 0 : item.Value;
            }

        }

    }
}